package com.zuul.simple.http;

import com.zuul.simple.filter.MyZuulFilter;
import com.zuul.simple.filter.post.SendResponseFilter;
import com.zuul.simple.filter.pre.RequestWrapperFilter;
import com.zuul.simple.filter.route.RoutingFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : kebukeyi
 * @date :  2021-05-21 11:33
 * @description : 这个是具体的执行器。需要说明一下，在Zuul中，ZuulRunner在获取具体有哪些过滤器的时候，有一个FileLoader可以动态读取配置加载。
 * @question :
 * @usinglink :
 **/
public class ZuulRunner {

    //静态写死过滤器
    private ConcurrentHashMap<String, ArrayList> hashFiltersByType = new ConcurrentHashMap<String, ArrayList>() {{
        put("pre", new ArrayList() {{
            add(new RequestWrapperFilter());
        }});
        put("route", new ArrayList() {{
            add(new RoutingFilter());

        }});
        put("post", new ArrayList() {{
            add(new SendResponseFilter());
        }});
    }};

    public void init(HttpServletRequest req, HttpServletResponse resp) {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.setRequest(req);
        ctx.setResponse(resp);
    }

    public void preRoute() throws Throwable {
        runFilters("pre");
    }

    public void route() throws Throwable {
        runFilters("route");

    }

    public void postRoute() throws Throwable {
        runFilters("post");

    }

    public void runFilters(String sType) throws Throwable {
        List<MyZuulFilter> list = this.hashFiltersByType.get(sType);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                MyZuulFilter filter = list.get(i);
                filter.run();
            }
        }
    }
}
 
